package rge.orumus.androidutils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.os.Environment;
import android.util.Base64;

public class AndroidUtils {
	
	public static final Charset UTF8CHARSET = Charset.forName("UTF-8");
	
	public static String ObjectToXmlString(Object object){
		
		String res = "";
		Serializer serializer = new Persister();

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {
			serializer.write(object, baos);
		} catch (Exception e) {
			res = "";
		}
		
		try {
			res = baos.toString("UTF-8");
		} catch (UnsupportedEncodingException e) {
			res = "";
		}
		
		return res;
	}
	
	public static String BytesToBase64Str(byte[] arr){
		return Base64.encodeToString(arr, Base64.DEFAULT);
	}

	public static byte[] Base64StrToBytes(String str){
		return Base64.decode(str, Base64.DEFAULT);
	}

    public static boolean isExternalStorageWritable() {
    	boolean externalStorageWriteable = false;
    	String state = Environment.getExternalStorageState();
    	if (Environment.MEDIA_MOUNTED.equals(state)) {
    	    externalStorageWriteable = true;
    	}
    	return externalStorageWriteable;
    }
    
    public static boolean isExternalStorageAvailable() {
		boolean externalStorageAvailable = false;
    	String state = Environment.getExternalStorageState();
    	if (Environment.MEDIA_MOUNTED.equals(state)) {
    		externalStorageAvailable = true;
    	} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    		externalStorageAvailable = true;
    	}
    	return externalStorageAvailable;
    }
    
    public static boolean ensureFolderExists(File f){
		if(!f.exists())
		{
			if(!f.mkdirs())
			{
				return false;
			}
		}
		
		return true;
    }

}
